const express = require('express')
const router = express.Router()

const dao = require('../dao/dao')

// 引入数据库
// const db = require('./login-router')

// 开放跨域请求
router.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  
    if (req.method == 'OPTIONS') {
      res.send(200); /让options请求快速返回/
    }
    else {
      next();
    }
  });


router.get('/', (req, res) => {     // 渲染主页面，并且通过 session 实现登录校验
    if(req.session.userName){  //判断session 状态，如果有效，则返回主页，否则转到登录页面
        res.render('index.html',{username : req.session.userName})
    }else{
        res.redirect('/login')
    }
})

router.get('/login', (req, res) => {    // 获取并渲染登录页面
    if(req.session.userName == undefined){
        return res.render('login.html', {
            tip: '用户登录信息已过期，请重新登录'
        })
    }
    res.render('login.html')
})

router.post('/login', (req, res) => {   // 校验账号密码是否正确，登录校验
    if(req.body == null){
        return
    }
    let user = req.body.userCode        // 用户输入的账号
    let pwd = req.body.userPassword     // 用户输入的密码
    dao.isLogin(user, pwd, (err, data) => {
        if(err){
            return res.send('404 Not Fount!')
        }
        if(data.length == 0){
            res.render('login.html', {
                tip: '账号或密码错误，请重试!'
            })
        } else {
            req.session.userName = req.body.userCode // 登录成功，设置 session
            res.redirect('/')
        }
    })
})

router.get('/out', (req, res) => {      // 退出登录，返回登录界面
    req.session.userName = ""
    res.redirect('/login')
})

router.get('/updataPwd', (req, res) => {    // 获取并渲染修改密码管理页面
    res.render('jsp/pwdmodify.html', {
        username: req.session.userName
    })
})

router.post('/updataPwd/getPwd', (req, res) => {    // 修改用户登录密码时，校验旧密码是否输入成功
    if(!req.session.userName){
        return res.send({code: 200, result: 'sessionerror'})
    }
    dao.isLogin(req.session.userName, req.body.oldpassword, (err, data) => {
        if(err){
            return res.send({code: 200, result: 'sessionerror'})
        }
        if(data.length === 0){
            return res.json({code: 200, result: 'false'})
        }

        return res.send({code: 200, result: 'true'})
    })
})

router.post('/updataPwd/setNewPwd', (req, res) => {     // 修改用户登录密码
    dao.updataPwdByOldPwd(req.session.userName, req.body.newpassword, (err, data) => {
        if(err){
            return res.status(500)
        }
        if(data.length !== 0){
            return res.redirect('/login')
        }
        return res.json({code: 200, msg: '修改密码失败！'})
    })
})

router.get('/supply', (req, res) => {   // 获取并渲染供应商管理页面
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.getProviderListAll((err, data) => {
        if(err){
            return 
        }
        res.render('jsp/providerlist.html', {
            username: req.session.userName,
            providerList: data
        })
    })
   
})

router.get('/addProvider', (req, res) => {  // 获取并渲染添加供应商页面
    if(!req.session.userName){
        res.redirect('/login')
    }
    res.render('jsp/provideradd.html', {
        username: req.session.userName
    })
})

router.post('/addProvider', (req, res) => {     // 添加供应商
    if(!req.session.userName){
        return res.redirect('login')
    }
    
    dao.addProvider(req.body, (err, data) => {
        if(err){
            return res.redirect('/login')
        }
        res.redirect('/supply')
    })
})

router.get('/deleteProvider', (req, res) => {   // 删除供应商信息
    if(!req.session.userName){
        return res.json({code: 200, delResult: 'false'})
    }
    dao.delProvider(req.query.proid, (err, data) => {
        if(err){
            return res.json({code: 200, delResult: 'false'})
        }
        if(data.length == 0){
            // 供应商不存在
            return res.json({code: 200, delResult: 'notexist'})
        }
        res.json({code: 200, delResult: 'true'})
    })
})

router.get('/modifyProvider', (req, res) => {   // 点击修改供应商信息，查找指定供应商的信息
    if(!req.session.userName){
        return res.redirect('/login')
    }
    
    dao.getProviderById(req.query.proid, (err, data) => {
        if(err){
            return 
        }
        res.render('jsp/providermodify.html', {
            username: req.session.userName,
            proInfo: data
        })
    })
})

router.post('/modifyProvider', (req, res) => {  // 处理修改指定供应商信息
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.updateProviderById(req.body.proid, req.body, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库错误'})
        }
        res.redirect('/supply')
    })

})

router.get('/viewmiaoshu', (req, res) => {      // 查看供应商描述
    if(!req.session.userName){
        return res.redirect('/login')
    }
    
    dao.getProviderById(req.query.proid, (err, data) => {
        if(err){
            return 
        }
        console.log(data)
        res.render('jsp/providerview.html', {
            username: req.session.userName,
            proInfo: data
        })
    })
})

router.get('/searchProviderList', (req, res) => {      // 按条件查询供应商
    if(!req.session.userName){
        return res.redirect('/login')
    }

    dao.searchProvider(req.query.queryProCode, req.query.queryProName, (err, data) => {
        if(err){
            return res.json({
                code: 500,
                msg: '数据库错误'
            })
        }
        res.render('jsp/providerlist.html', {
            username: req.session.userName,
            providerList: data,
            queryProCode: req.query.queryProCode || "",
            queryProName: req.query.queryProName || ""
        })
    })
})



router.get('/people', (req, res) => {   // 获取并渲染用户管理页面
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.getCount({}, (err1, data1) => {
        if(err1){
            return res.json({code: 500, msg: '数据库错误'})
        }
        dao.getUser(pageIndex = req.query.pageIndex, (err, data) => {
            if(err){
                return res.json({code: 500, msg: '数据库错误'})
            }
            console.log(req.query.pageIndex)
            res.render('jsp/userlist.html', {
                username: req.session.userName,
                userList: data,
                total: data1,
                pageCount: Math.ceil((data1 / 10)),
                pageIndex: req.query.pageIndex || 1
                
            })
        })
    })
    
})

router.get('/getRoleList', (req, res) => {      // 获取角色列表
    // if(!req.session.userName){
    //     return res.json({code: 400, msg: '登录身份已失效，请重新登录'})
    // }
    dao.getAllRole((err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.json({
            code: 200,
            data: data
        })
    })

})

router.get('/checkCode', (req, res) => {        // 校验用户编码是否可用
    if(!req.session.userName){
        return res.redirect('/login')
    }

    if(!req.query.userCode.trim()){
        return
    }
    dao.checkedCode(req.query.userCode, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        if(!data){
            return res.json({code: 200, userCode: 'un_exist'})
        }
        res.json({code: 200, userCode: 'exist'})
    })
})

router.post('/adduser', (req, res) => {     // 注册新用户
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.addUser(req.body, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.redirect('/people')
    })

})

router.get('/delUser', (req, res) => {      // 删除指定用户
    if(!req.session.userName){
        return res.redirect('/login')
    }
    let id = req.query.uid.slice(1, req.query.uid.length -1)
    dao.delUser(id, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.json({code: 200, delResult: 'true'})
    })
})

router.get('/viewUser', (req, res) => {     // 查找指定用户信息
    if(!req.session.userName){
        return res.redirect('/login')
    }

    let id = req.query.uid.slice(1, req.query.uid.length - 1)
    dao.viewUser(id, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.render('jsp/userview.html', {
            username: req.session.userName,
            userInfo: data
        })
    })
})

router.get('/updateUser', (req, res) => {   // 点击修改操作渲染更新指定用户页面
    if(!req.session.userName){
        return res.redirect('/login')
    }

    let id = req.query.uid.slice(1, req.query.uid.length - 1)

    dao.viewUser(id, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.render('jsp/usermodify.html', {
            username: req.session.userName,
            userInfo: data
        })
    })

})

router.post('/updateUser', (req, res) => {      // 修改保存页面信息
    if(!req.session.userName){
        return res.redirect('/login')
    }

    dao.updateUser(req.body, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.redirect('/people')
    })
})

router.get('/selUser', (req, res) => {      // 按条件查询列表
    if(!req.session.userName){
        return res.redirect('/login')
    }
    let opt = {}
    if(req.query.queryname.trim().length !== 0){
        opt.userName = req.query.queryname
    }
    if(req.query.queryUserRole !== '0'){
        opt.role = req.query.queryUserRole
    }

    dao.getCount({}, (err1, data1) => {
        if(err1){
            return res.json({code: 500, msg: '数据库错误'})
        }
        dao.getUser(pageIndex = req.query.pageIndex, (err, data) => {
            if(err){
                return res.json({code: 500, msg: '数据库错误'})
            }
            res.render('jsp/userlist.html', {
                username: req.session.userName,
                userList: data,
                total: data1,
                pageCount: Math.ceil((data1 / 10)),
                pageIndex: req.query.pageIndex || 1
            })
        }, opt)
    }, opt)
})






router.get('/order', (req, res) => {    // 获取并渲染订单管理页面
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.getOrder((err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.render('jsp/billlist.html', {
            username: req.session.userName,
            orderList: data
        })
    })
    
})

router.get('/showAddOrder', (req, res) => {     // 渲染添加订单页面
    if(!req.session.userName){
        return res.redirect('/login')
    }

    res.render('jsp/billadd.html')
})

router.get('/getProviderNameList', (req,res) => {       // 获取供应商列表
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.getProviderNameList((err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.json({code: 200, res: data})
    })
})

router.post('/addOrder', (req, res) => {        // 添加新订单
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.addOrder(req.body, (err, data) => {
        if(err){
            return res.render('jsp/billadd.html', {
                tip: '订单号已存在，请重新输入数据'
            })
        }
        res.redirect('/order')
    })
})

router.get('/viewOrder',  (req, res) => {       // 展示指定Id的订单
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.viewOrder(req.query.billid, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.render('jsp/billview.html', {
            username: req.session.userName,
            orderInfo: data
        })
    })
})

router.get('/updateOrder', (req, res) => {      // 获取指定ID信息并渲染页面
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.viewOrder(req.query.billid, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库错误'})
        }
        res.render('jsp/billmodify.html', {
            username: req.session.userName,
            orderInfo: data
        })
    })
})

router.post('/updateOrder', (req, res) => {     // 修改指定ID的信息
    if(!req.session.userName){
        return res.redirect('/login')
    }
    dao.updateOrder(req.body, (err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        res.redirect('/order')
    })
})

router.get('/selOrder', (req, res) => {     // 按条件查询订单列表
    if(!req.session.userName){
        return res.redirect('/login')
    }
    let opt = {}
    if(req.query.queryProductName.trim().length !== 0){
        opt.orderName = req.query.queryProductName
    }
    if(req.query.queryProviderId !== '0'){
        opt.providerName = req.query.queryProviderId
    }
    if(req.query.queryIsPayment !== '0'){
        opt.isPay = req.query.queryIsPayment
    }
    dao.getOrder((err, data) => {
        if(err){
            return res.json({code: 500, msg: '数据库出错'})
        }
        console.log(data)
        res.render('jsp/billlist.html', {
            username: req.session.userName,
            orderList: data
        })
    },opt)
})






module.exports = router